<template>
  <div class="app-container">
    <el-card>
      <title-line title="添加管理员" />
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="头像：" prop="avatar">
              <upload-image
                :isShowTip="true"
                :lazy="true"
                :file-type="['jpg', 'png', 'jpeg']"
                :file-size="1"
                :response-fn="handleResponse"
                @on-change="uploadChange"
                v-model="formData.avatar"
              />
            </el-form-item>
            <el-form-item label="所属类型：" required>
              <el-select
                v-model="type_status"
                placeholder="请选择所属类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in TypeStatus"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="登录账号：" prop="userName">
              <el-input
                v-model="formData.userName"
                :disabled="type === 'update'"
                placeholder="请输入登录账号，字母或数字（6-20位以内）"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item v-if="type !== 'update'" label="登录密码：" prop="password">
              <el-input
                v-model="formData.password"
                show-password
                placeholder="请输入登录密码"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item v-else>
              <el-button type="primary" @click="updatePassword"> 修改密码 </el-button>
            </el-form-item>
            <el-form-item label="所属角色：" prop="roleId">
              <el-select
                v-model="formData.roleId"
                placeholder="请选择所属角色"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="(item, index) in roleSelectList"
                  :key="index"
                  :label="item.roleName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="真实姓名：" prop="realName">
              <el-input
                v-model="formData.realName"
                placeholder="请输入管理员真实姓名（1-5个字符，只能输入中文）"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item label="联系电话：" prop="telephone">
              <el-input v-model="formData.telephone" placeholder="请输入员工联系电话" clearable>
              </el-input>
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱号" clearable> </el-input>
            </el-form-item>
            <el-form-item label="是否启用：" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="(item, index) in STATUS" :key="index" :label="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button @click="resetForm"> 取消 </el-button>
              <el-button type="primary" :loading="loading" @click="submitForm"> 保存 </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <password-popup v-if="visible" :dialogVisible.sync="visible" />
  </div>
</template>
<script>
import md5 from 'js-md5'
import { STATUS } from '@/enum'
import rules from './add-admin-rules'
import { mapActions, mapState } from 'vuex'
import PasswordPopup from './component/password-popup.vue'
export default {
  components: { PasswordPopup },
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      formData: {
        avatar: '',
        email: '',
        password: '',
        realName: '',
        roleId: '',
        status: 1,
        telephone: '',
        userName: ''
      },
      roleList: [],
      TypeStatus: [
        {
          id: '',
          label: '平台管理员'
        }
      ],
      type_status: ''
    }
  },
  computed: {
    ...mapState('base', ['roleSelectList']),
    STATUS() {
      return STATUS
    },
    rules() {
      return rules
    },
    type() {
      return this.$route.query.type
    }
  },
  created() {
    this.getRoleSelect()
    this.getDetail()
  },
  mounted() {},
  methods: {
    ...mapActions('base', ['getRoleSelect']),
    // 新增
    async add() {
      const params = { ...this.formData, password: md5(this.formData.password) }
      const { status, msg } = await this.$http.system.admin.add(params)
      if (status === 200) {
        this.$message.success('添加成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // 编辑
    async updated() {
      const { id } = this.$route.query
      const { status, msg } = await this.$http.system.admin.update({
        ...this.formData,
        id
      })
      if (status === 200) {
        this.$message.success('编辑成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    },
    // type: 'update'获取详情
    async getDetail() {
      const { id, type } = this.$route.query
      if (!type) return
      const { data } = await this.$http.system.admin.getDetail(id)
      for (const key in this.formData) {
        this.formData[key] = data[key]
      }
    },
    // 修改密码
    updatePassword() {
      this.visible = true
    },
    // 确定
    submitForm() {
      const { type } = this.$route.query
      console.log(this.formData)
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.loading = true
        if (type === 'update') {
          this.updated()
        } else {
          this.add()
        }
        this.loading = false
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    },
    handleResponse(response) {
      return response
    },
    uploadChange() {
      if (this.formData.avatar) {
        this.$refs.elForm.validateField('avatar')
      }
    }
  }
}
</script>
<style></style>
